package seatiger.tomcat.util;

import java.text.MessageFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * 国际化资源 管理
 */
public class StringManager {

    /**
     * 缓存，一个包 对应一个管理器
     */
    private static Map<String,StringManager> managers = new ConcurrentHashMap<>();

    /**
     * 负责处理国际化资源
     */
    private ResourceBundle bundle;

    private StringManager(String packageName) {
        String bundleName = packageName + ".LocalStrings";
        bundle = ResourceBundle.getBundle(bundleName);
    }

    public String getString(String key,Object... objs){
        String value = getString(key);
        if (objs == null || objs.length == 0){
            return value;
        }
        Object[] nonNullArgs = Arrays.stream(objs).map(obj -> {
            if (obj == null) {
                return "null";
            }
            return obj;
        }).collect(Collectors.toList()).toArray();
        try {
            value = MessageFormat.format(value, nonNullArgs);
        }catch (IllegalArgumentException iae){
            StringBuilder builder = new StringBuilder(value);
            for (int i = 0; i < objs.length; i++) {
                builder.append(" arg[" + i + "]=" + objs[i]);
            }
            return builder.toString();
        }

        return value;
    }



    public String getString(String key) {
        if (key == null) {
            throw new NullPointerException("key is null");
        }
        String str = null;
        try {
            str = bundle.getString(key);
        } catch (MissingResourceException mre) {
            str = "Cannot find message associated with key '" + key + "'";
        }
        return str;
    }

    public synchronized static StringManager getManager(String packageName){
        return managers.computeIfAbsent(packageName, StringManager::new);
    }
}
